package com.yonyou.cyxdms.sysAuth.service.service.vehicleProduct;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.dto.DealerBrandDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.vehicleBrand.BrandCacheDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.vehicleBrand.DealerBrandListDTO;
import com.yonyou.cyxdms.sysAuth.service.entity.DealerBrandPO;
import com.yonyou.cyxdms.sysAuth.service.feign.BaseDataService;
import com.yonyou.cyxdms.sysAuth.service.mapper.DealerBrandMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.DealerInfoMapper;
import com.yonyou.cyxdms.sysAuth.service.vo.vehicleProduct.DealerBrandVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author     ：quankk
 * @date       ：2019/7/9 15:46
 * @description：
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DealerbrandServiceImpl implements DealerbrandService {

    // 定义日志接口
    private static final Logger logger = LoggerFactory.getLogger(DealerbrandServiceImpl.class);

    @Autowired
    private DealerBrandMapper dealerBrandMapper;

    @Autowired
    private BaseDataService baseDataService;

    @Autowired
    private DealerInfoMapper dealerBasicinfoMapper;

    /**
     * @author     ：quankk
     * @date       ：2019/7/17 15:44
     * @description：
     */
    @Override
    public IPage<DealerBrandVO> querydealerBrand(Page<DealerBrandVO> page, Map<String, String> param) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        param.put("loginDealerCode",loginInfoDto.getOwnerCode());
        param.put("appId",loginInfoDto.getAppId());
        List<DealerBrandVO> list = dealerBrandMapper.querydealerBrand(page, param);
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("dealerCode",loginInfoDto.getOwnerCode());
        List<BrandCacheDTO> brandCacheDTOList = baseDataService.queryBrandByCondition(queryParam).getData();
        if(!CommonUtils.isNullOrEmpty(brandCacheDTOList)){
            list.stream().forEach(dealerBrandVO -> {
                for(BrandCacheDTO brandCacheDTO : brandCacheDTOList){
                    if(brandCacheDTO.getBrandId().equals(dealerBrandVO.getBrandId())){
                        dealerBrandVO.setBrandName(brandCacheDTO.getBrandName());
                        break;
                    }
                }
            });
        }

        page.setRecords(list);
        return page;
    }

    /**
     * @author     ：quankk
     * @date       ：2019/7/17 17:56
     * @description：新增关联信息
     */
    @Override
    public Integer addRelation(DealerBrandDTO dbDto) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        DealerBrandPO dbPo = new DealerBrandPO();
        String brandCode;
        if (StringUtils.isNullOrEmpty(dbDto.getBrandCode())) {
            Map<String, Object> queryParam = new HashMap<>();
            queryParam.put("dealerCode",loginInfoDto.getOwnerCode());
            queryParam.put("brandId",dbDto.getBrandId());
            List<BrandCacheDTO> brandCacheDTOList = baseDataService.queryBrandByCondition(queryParam).getData();
            brandCode =brandCacheDTOList.get(0).getBrandCode();
        }else {
            brandCode = dbDto.getBrandCode();
        }
        LambdaQueryWrapper<DealerBrandPO> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(DealerBrandPO :: getDlrCode, dbDto.getDataSources())
                .eq(DealerBrandPO :: getBrandCode, brandCode);
        List<DealerBrandPO> list = dealerBrandMapper.selectList(queryWrapper);
        if(!CommonUtils.isNullOrEmpty(list)) {
            throw new ServiceBizException("已存在相同的品牌与经销商关系");
        }
        dbPo.setDlrCode(dbDto.getDealerCode());
        dbPo.setBrandCode(brandCode);
        dbPo.setIsRelated(SysAuthDictCodeConstants.STATUS_IS_NOT);
        dbPo.setBrandId(dbDto.getBrandId());
        dbPo.setPrimaryBrand(SysAuthDictCodeConstants.STATUS_IS_NOT);
        dbPo.setOrgId(dbDto.getOrgId());
        dealerBrandMapper.insert(dbPo);
        return dbPo.getRelationId();
    }

    /**
     * @author     ：quankk
     * @date       ：2019/7/17 18:31
     * @description：
     */
    @Override
    public void relateDealerBrand(DealerBrandListDTO dealerBrandDto) {
        for (int i = 0; i < dealerBrandDto.getDealerbrandlist().size(); i++) {
            Long relationId=Long.valueOf(dealerBrandDto.getDealerbrandlist().get(i).getRelationId());
            DealerBrandPO dealerbrandPo = dealerBrandMapper.selectById(relationId);
            dealerbrandPo.setIsRelated(SysAuthDictCodeConstants.STATUS_IS_YES);
            dealerBrandMapper.updateById(dealerbrandPo);
        }
    }

    /**
     * @author     ：quankk
     * @date       ：2019/7/18 10:34
     * @description： 删除关联信息
     */
    @Override
    public void deleteRelate(Integer id) {
        dealerBrandMapper.deleteById(id);
    }

    /**
     * @author     ：quankk
     * @date       ：2019/7/18 10:56
     * @description：设置车辆主数据
     */
    @Override
    public void primaryDealerBrand(Integer id) {
        DealerBrandPO dealerbrandpo = dealerBrandMapper.selectById(id);
        if(dealerbrandpo.getIsRelated()!=SysAuthDictCodeConstants.STATUS_IS_YES){
            throw new ServiceBizException("未关联的品牌不可设置为主品牌！");
        }
        String dlrCode = dealerbrandpo.getDlrCode();
        LambdaQueryWrapper<DealerBrandPO> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(DealerBrandPO :: getDlrCode, dlrCode);
        List<DealerBrandPO> list = dealerBrandMapper.selectList(queryWrapper);
        for(DealerBrandPO map:list){
            Integer primaryDate = map.getPrimaryBrand();
            Integer relationId = map.getRelationId();
            if(!ObjectUtils.isEmpty(primaryDate)) {
                if (SysAuthDictCodeConstants.STATUS_IS_YES == primaryDate) {
                    DealerBrandPO dealerbrandpo2 = dealerBrandMapper.selectById(relationId);
                    dealerbrandpo2.setPrimaryBrand(SysAuthDictCodeConstants.STATUS_IS_NOT);
                    dealerBrandMapper.updateById(dealerbrandpo2);
                }
            }
        }
        dealerbrandpo.setPrimaryBrand(SysAuthDictCodeConstants.STATUS_IS_YES);
        dealerBrandMapper.updateById(dealerbrandpo);
    }

    /**
     * @author     ：quankk
     * @date       ：2019/7/19 17:14
     * @description：经销商下拉框的方法
     */
    @Override
    public List<Map> queryDealer(Map<String, String> queryParam) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return dealerBrandMapper.queryDealer(loginInfoDto.getAppId(), loginInfoDto.getOwnerCode());
    }

    /**
     * @author     ：quankk
     * @date       ：2019/7/19 17:24
     * @description：经销商下拉框的方法
     */
    @Override
    public List<Map> queryBrand2(Map<String, String> queryParam) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> param = new HashMap<>();
        param.put("appId", loginInfoDto.getAppId());
        param.put("dealerCode", loginInfoDto.getOwnerCode());
        return baseDataService.queryBrand2(param).getData();
    }

    @Override
    public List<Long> queryBrandIdListByOwnerCode(String ownerCode) {
        return dealerBrandMapper.queryBrandIdListByOwnerCode(ownerCode);
    }

    /**
     * 获取维修站简称
     *
     * @param
     * @return java.util.List<java.util.Map   <   java.lang.String   ,   java.lang.Object>>
     * @author dengqiang
     * @since 2019/8/19
     */
    @Override
    public List<Map<String, Object>> queryDealerShortname() {
        return dealerBasicinfoMapper.queryDealerShortname();
    }


    /**
     * 获取品牌ID列表
     *
     * @param
     * @return java.util.List<java.lang.Long>
     * @author dengqiang
     * @since 2019/8/19
     */
    @Override
    public List<Long> queryBrandIdList() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String ownerCode = loginInfoDto.getOwnerCode();
        return dealerBrandMapper.queryBrandIdList(ownerCode);
    }

    /**
     * 获取车系ID列表
     *
     * @author 李贺
     * @since 2019/12/11
     */
    @Override
    public List<Long> querySeriesIdList() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String ownerCode = loginInfoDto.getOwnerCode();
        return dealerBrandMapper.querySeriesIdList(ownerCode);
    }

}
